<template>
  <header class="unified-navbar">
    <div class="nav-left">


      <div class="logo-section">

        <h1 class="platform-title">{{ platformTitle }}</h1>
      </div>

      <nav class="nav-tabs">
        <div
            v-for="(tab, index) in navTabs"
            :key="index"
            class="nav-tab"
            :class="{ active: tab.active }"
            @click="navigateToTab(tab)"
        >
          {{ tab.name }}
        </div>
      </nav>
    </div>

    <div class="nav-right">
      <div class="user-profile" @click="toggleUserMenu">
        <div class="user-info">
          <div v-if="userInfo.loading" class="user-name loading">加载中...</div>
          <div v-else class="user-name">{{ userInfo.username }}</div>
          <div v-if="!userInfo.loading" class="user-role">{{ userRoleText }}</div>
        </div>        <div class="user-avatar">
          <span class="avatar-text" v-if="!userInfo.loading && userInfo.username">{{ userInfo.username.charAt(0).toUpperCase() }}</span>
          <span class="avatar-text" v-else>?</span>
        </div>
      </div>

      <!-- 用户下拉菜单 -->
      <div v-if="showUserMenu" class="user-dropdown" @click.stop>
        <div class="dropdown-item" @click="navigateToPersonalInfo">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M8 8C10.2091 8 12 6.20914 12 4C12 1.79086 10.2091 0 8 0C5.79086 0 4 1.79086 4 4C4 6.20914 5.79086 8 8 8Z" fill="currentColor"/>
            <path d="M8 10C3.58172 10 0 13.5817 0 18H16C16 13.5817 12.4183 10 8 10Z" fill="currentColor"/>
          </svg>
          个人信息
        </div>
        <div class="dropdown-divider"></div>
        <div class="dropdown-item logout" @click="handleLogout">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M6 14H3C2.73478 14 2.48043 13.8946 2.29289 13.7071C2.10536 13.5196 2 13.2652 2 13V3C2 2.73478 2.10536 2.48043 2.29289 2.29289C2.48043 2.10536 2.73478 2 3 2H6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M11 11L14 8L11 5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M14 8H6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          退出登录
        </div>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div v-if="showUserMenu" class="dropdown-overlay" @click="closeUserMenu"></div>
  </header>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuth } from '@/composables/useAuth'
import getPersonalInfoAPI from '@/apis/authAPI/getPersonalInfoAPI'

interface PersonalInfoResponse {
  code: number
  message: string
  data: {
    id: number
    username: string
    email: string
    avatar: string
    role: string
  }
}

interface NavTab {
  name: string
  route: string
  active: boolean
  permission?: string[]
}

const router = useRouter()
const route = useRoute()
const { logout, userRole } = useAuth()

const showUserMenu = ref(false)
const userInfo = ref({
  loading: true,
  id: '',
  username: '',
  avatar: '',
  role: ''
})

// 根据用户角色显示不同的平台标题
const platformTitle = computed(() => {
  return userRole.value === 'teacher' ? '教师管理平台' : '学生学习平台'
})

// 用户角色文本
const userRoleText = computed(() => {
  return userRole.value === 'teacher' ? '教师' : '学生'
})

// 根据用户角色显示不同的导航标签
const navTabs = computed((): NavTab[] => {
  if (userRole.value === 'teacher') {
    return [
      { name: '教学管理中心', route: '/teacher-home', active: route.path === '/teacher-home' },
      { name: 'AI资源中心', route: '/chat', active: route.path === '/chat' },
      { name: '题库管理', route: '/question-repo', active: route.path === '/question-repo' },
      { name: '资源管理', route: '/resource-repo', active: route.path === '/resource-repo' }
    ]
  } else {
    return [
      { name: '学习中心', route: '/student-home', active: route.path === '/student-home' },
      { name: '考试中心', route: '/student-exam', active: route.path === '/student-exam' },
      { name: 'AI聊天', route: '/student-chat', active: route.path === '/student-chat' }
    ]
  }
})

// 切换侧边栏（发送事件给父组件）
const emit = defineEmits(['toggle-sidebar'])
const toggleSidebar = () => {
  emit('toggle-sidebar')
}

// 导航到标签页
const navigateToTab = (tab: NavTab) => {
  router.push(tab.route)
}

// 切换用户菜单
const toggleUserMenu = () => {
  showUserMenu.value = !showUserMenu.value
}

// 关闭用户菜单
const closeUserMenu = () => {
  showUserMenu.value = false
}

// 导航到个人信息
const navigateToPersonalInfo = () => {
  router.push('/personal-info')
  closeUserMenu()
}

// 导航到设置
const navigateToSettings = () => {
  // 可以根据需要添加设置页面
  console.log('导航到设置页面')
  closeUserMenu()
}

// 处理退出登录
const handleLogout = async () => {
  await logout()
  closeUserMenu()
}

// 获取用户信息
const getUserInfo = async () => {
  try {
    userInfo.value.loading = true
    console.log('开始获取用户信息...')
    
    // 首先尝试从localStorage获取缓存的用户信息
    const cachedUserInfo = localStorage.getItem('userInfo')
    const cachedRole = localStorage.getItem('role')
    
    if (cachedUserInfo) {
      try {
        const parsedUserInfo = JSON.parse(cachedUserInfo)
        console.log('从localStorage获取到用户信息:', parsedUserInfo)
        
        userInfo.value = {
          loading: false,
          id: parsedUserInfo.id?.toString() || '',
          username: parsedUserInfo.username || '',
          avatar: parsedUserInfo.avatar || '',
          role: parsedUserInfo.role || cachedRole || ''
        }
        console.log('使用缓存的用户信息:', userInfo.value)
        
        // 如果有缓存信息，先显示缓存信息，然后异步更新
        try {
          const response = await getPersonalInfoAPI() as PersonalInfoResponse
          console.log('用户信息API响应:', response)
          
          if (response.code === 200) {
            userInfo.value = {
              loading: false,
              id: response.data.id.toString(),
              username: response.data.username,
              avatar: response.data.avatar,
              role: response.data.role
            }
            // 更新localStorage
            localStorage.setItem('userInfo', JSON.stringify(response.data))
            console.log('用户信息更新成功:', userInfo.value)
          }
        } catch (apiError) {
          console.warn('API更新用户信息失败，使用缓存信息:', apiError)
        }
        
        return
      } catch (parseError) {
        console.error('解析缓存用户信息失败:', parseError)
      }
    }
    
    // 如果没有缓存信息，尝试API获取
    try {
      const response = await getPersonalInfoAPI() as PersonalInfoResponse
      console.log('用户信息API响应:', response)
      
      if (response.code === 200) {
        userInfo.value = {
          loading: false,
          id: response.data.id.toString(),
          username: response.data.username,
          avatar: response.data.avatar,
          role: response.data.role
        }
        // 保存到localStorage
        localStorage.setItem('userInfo', JSON.stringify(response.data))
        console.log('用户信息设置成功:', userInfo.value)
      } else {
        throw new Error(response.message || '获取用户信息失败')
      }
    } catch (apiError) {
      console.error('API获取用户信息失败:', apiError)
      
      // 如果API失败，尝试使用基本的localStorage信息
      const userId = localStorage.getItem('id')
      const userRole = localStorage.getItem('role')
      
      if (userId && userRole) {
        userInfo.value = {
          loading: false,
          id: userId,
          username: userRole === 'teacher' ? '教师' : '学生',
          avatar: '',
          role: userRole
        }
        console.log('使用基本localStorage信息:', userInfo.value)
      } else {
        userInfo.value = {
          loading: false,
          id: '',
          username: '用户',
          avatar: '',
          role: ''
        }
        console.log('使用默认用户信息')
      }
    }
  } catch (error) {
    console.error('获取用户信息过程出错:', error)
    userInfo.value = {
      loading: false,
      id: '',
      username: '用户',
      avatar: '',
      role: ''
    }
  }
}

// 点击外部关闭菜单
const handleClickOutside = (event: Event) => {
  if (showUserMenu.value && !(event.target as Element).closest('.user-profile')) {
    closeUserMenu()
  }
}

onMounted(() => {
  getUserInfo()
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.unified-navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #ffffff;
  color: #2c2c2c;
  padding: 0 24px;
  height: 64px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1000;
  border-bottom: 1px solid #f0f0f0;
}

.nav-left {
  display: flex;
  align-items: center;
  gap: 24px;
}

.nav-icon {
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: all 0.2s ease;
  color: #666;
}

.nav-icon:hover {
  background-color: #f5f5f5;
  color: #333;
}

.icon-inner {
  display: block;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.system-logo {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
}

.logo-icon {
  opacity: 0.9;
}

.platform-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #2c2c2c;
}

.nav-tabs {
  display: flex;
  gap: 8px;
}

.nav-tab {
  padding: 8px 16px;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.2s ease;
  font-weight: 500;
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.nav-tab:hover {
  background-color: #f5f5f5;
  color: #333;
}

.nav-tab.active {
  background-color: #667eea;
  color: white;
  font-weight: 600;
}

.nav-right {
  position: relative;
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.user-profile:hover {
  background-color: #f5f5f5;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  text-align: right;
}

.user-name {
  font-weight: 600;
  margin: 0;
  font-size: 14px;
  color: #2c2c2c;
}

.user-name.loading {
  color: #999;
}

.user-role {
  font-size: 12px;
  color: #666;
  margin: 0;
}

.user-avatar {
  width: 32px;
  height: 32px;
  background: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  border: 2px solid #f0f0f0;
}

.avatar-text {
  color: #2C2C2C;
  font-size: 14px;
  font-family: Inter, sans-serif;
  font-weight: 700;
}

.user-dropdown {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 8px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  min-width: 180px;
  overflow: hidden;
  z-index: 1001;
  border: 1px solid #f0f0f0;
}

.dropdown-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  color: #333;
  cursor: pointer;
  transition: background-color 0.2s ease;
  font-size: 14px;
}

.dropdown-item:hover {
  background-color: #f5f5f5;
}

.dropdown-item.logout {
  color: #e74c3c;
}

.dropdown-item.logout:hover {
  background-color: #ffeaea;
}

.dropdown-divider {
  height: 1px;
  background-color: #f0f0f0;
  margin: 4px 0;
}

.dropdown-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .nav-tabs {
    display: none;
  }

  .platform-title {
    font-size: 16px;
  }
}

@media (max-width: 768px) {
  .unified-navbar {
    padding: 0 16px;
    height: 56px;
  }

  .nav-left {
    gap: 16px;
  }

  .logo-section {
    gap: 8px;
  }

  .platform-title {
    font-size: 16px;
  }

  .user-info {
    display: none;
  }

  .user-avatar {
    width: 28px;
    height: 28px;
  }
}
</style>
